package com.example.myjavafx.controller;

import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.TextField;
import javafx.scene.control.TextArea;
import com.example.myjavafx.service.ApiService;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class LightSourceController {
    @FXML
    public TextField lightId;
    @FXML
    private TextField port;
    @FXML
    private TextField baudrate;
    @FXML private TextField deviceAddressField;
    @FXML private Label connectionStatusLabel;
    @FXML private Slider brightnessSlider;
    @FXML private TextArea responseTextArea;

    String baseUrl = "http://192.168.0.173:12345/api/control";

    private ApiService apiService;
    private HttpClient httpClient;
    private Gson gson;

    public void initialize() {
        apiService = new ApiService();
        httpClient = HttpClient.newHttpClient();
        gson = new Gson();
    }

    /***
     * 光源初始化方法
     */
    @FXML
    private void initializeDevice() {
        JsonObject requestBody = new JsonObject();
        // 参数有model, class_name, function_name
        requestBody.addProperty("mode", "initialize");
        requestBody.addProperty("class_name", "KemaiLightController");
        requestBody.addProperty("function_name", "");

        sendPostRequest("/light/init", requestBody);
//        connectionStatusLabel.setText("初始化成功");
    }

    /**
     * 连接设备方法
     * {
     * "class_name":"KemaiLightController",
     * "mode":"invoking",
     * "function_name":"connect",
     * "port":"COM3",
     * "baudrate":9600,
     * "timeout":1.0
     * }
     */
    @FXML
    private void connectDevice() {
//        String deviceAddress = deviceAddressField.getText();
//        if (deviceAddress.isEmpty()) {
//            showAlert("请输入设备地址");
//            return;
//        }
        // 构建请求体，包含设备地址等信息
        JsonObject requestBody = new JsonObject();
//        requestBody.addProperty("address", deviceAddress);
        requestBody.addProperty("class_name", "KemaiLightController");
        requestBody.addProperty("mode", "invoking");

        requestBody.addProperty("function_name", "connect");
        requestBody.addProperty("port", port.getText());
        requestBody.addProperty("baudrate", baudrate.getText().isEmpty() ? 9600 : Integer.parseInt(baudrate.getText()));
//        requestBody.addProperty("timeout", "1.0");

        sendPostRequest("/light/connect", requestBody);
//        connectionStatusLabel.setText("连接成功");
    }

    /**
     * 打开光源
     * {
     * "class_name":"KemaiLightController",
     * "mode":"invoking",
     * "function_name":"turn_on",
     * "light_id":1
     * }
     */
    @FXML
    private void turnOnLight() {
        JsonObject requestBody = new JsonObject();
        requestBody.addProperty("mode", "invoking");
        requestBody.addProperty("class_name", "KemaiLightController");
        requestBody.addProperty("function_name", "turn_on");
        requestBody.addProperty("light_id", 1);
//        requestBody.addProperty("light_id", lightId.getText().isEmpty() ? 1 : Integer.parseInt(lightId.getText()));

        sendPostRequest("/light/on", requestBody);
    }

    /**
     * 关闭光源
     * {
     * "class_name":"KemaiLightController",
     * "mode":"invoking",
     * "function_name":"turn_off",
     * "light_id":1
     * }
     */
    @FXML
    private void turnOffLight() {
        JsonObject requestBody = new JsonObject();
        requestBody.addProperty("mode", "invoking");
        requestBody.addProperty("class_name", "KemaiLightController");
        requestBody.addProperty("function_name", "turn_off");
        requestBody.addProperty("light_id", 1);
//        requestBody.addProperty("light_id", lightId.getText().isEmpty() ? 1 : Integer.parseInt(lightId.getText()));
        sendPostRequest("/light/off", requestBody);
    }

    /**
     * 断开设备连接
     * {
     * "class_name":"KemaiLightController",
     * "mode":"invoking",
     * "function_name":"disconnect"
     * }
     */
    @FXML
    private void disconnectDevice() {
        JsonObject requestBody = new JsonObject();
        requestBody.addProperty("mode", "invoking");
        requestBody.addProperty("class_name", "KemaiLightController");
        requestBody.addProperty("function_name", "disconnect");
        sendPostRequest("/light/disconnect", requestBody);
    }

    /**
     * 调整亮度
     * {
     * "class_name":"KemaiLightController",
     * "mode":"invoking",
     * "function_name":"set_brightness",
     * "brightness":100,
     * "light_id":1
     * }
     */
    @FXML
    private void adjustBrightness() {
        int brightness = (int) brightnessSlider.getValue();
        JsonObject requestBody = new JsonObject();
        requestBody.addProperty("brightness", brightness);
        requestBody.addProperty("mode", "invoking");
        requestBody.addProperty("class_name", "KemaiLightController");
        requestBody.addProperty("function_name", "set_brightness");
        requestBody.addProperty("light_id", 1);
//        requestBody.addProperty("light_id", lightId.getText().isEmpty() ? 1 : Integer.parseInt(lightId.getText()));

        sendPostRequest("/light/brightness", requestBody);
    }

    /**
     * 发送POST请求的方法
     * @param endpoint --请求的端点
     * @param requestBody --请求体
     */

    private void sendPostRequest(String endpoint, JsonObject requestBody) {
//        String baseUrl = deviceAddressField.getText();
//        if (baseUrl.isEmpty()) {
//            showAlert("请先输入设备地址");
//            return;
//        }

        try {
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(baseUrl))
                    .header("Content-Type", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString(requestBody.toString()))
                    .build();

            // 发送异步请求，并在UI线程中更新响应
            httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
                    .thenAccept(response -> Platform.runLater(() -> {
                        int statusCode = response.statusCode();
                        String responseBody = response.body();
                        updateUIWithResponse(statusCode, responseBody);
                    })).exceptionally(e -> {
                        // 异常处理，更新UI显示错误信息
                        Platform.runLater(() -> responseTextArea.setText("请求发送失败: " + e.getMessage()));

                   return null; });

            //.exceptionally(e -> {
            //                    Platform.runLater(() -> onError.accept("请求失败: " + e.getMessage()));
            //                    return null;
            //                });
        } catch (Exception e) {
            Platform.runLater(() -> {
                responseTextArea.setText("请求发送失败");
            });
//            showAlert("错误", "请求发送失败: " + e.getMessage());
        }
    }

    private void updateUIWithResponse(int statusCode, String responseBody) {
        responseTextArea.setText("状态码: " + statusCode + "\n响应内容: " + responseBody);

        if (statusCode == 200) {
            try {
                JsonObject jsonResponse = gson.fromJson(responseBody, JsonObject.class);
                if (jsonResponse.has("message")) {
//                    jsonResponse.get("status").getAsString();
                    connectionStatusLabel.setText(jsonResponse.get("code").getAsString());
                }
            } catch (Exception e) {
                // JSON解析失败，不做处理
            }
        }
    }

    private void showAlert(String content) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("错误");
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }
}